package com.fmatos.amazingwallpapers.wallpaper.domain;

import java.util.ArrayList;
import java.util.List;

import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;

public class WallpaperCircles implements AmazingWallpaper {

	
	private static final String TAG = "WallpaperCircles";
	private List<MyPoint> circles;
	private Paint paint = new Paint();
	private int width;
	private int height;
	
	private int maxNumber;
	private boolean touchEnabled;
	
	public WallpaperCircles(SharedPreferences prefs) {
		
		maxNumber = Integer.valueOf(prefs.getString("numberOfCircles", "4"));
		touchEnabled = prefs.getBoolean("touch", true);
		circles = new ArrayList<MyPoint>();
		paint.setAntiAlias(true);
		paint.setColor(Color.WHITE);
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeJoin(Paint.Join.ROUND);
		paint.setStrokeWidth(10f);
	}

	/* (non-Javadoc)
	 * @see com.fmatos.amazingwallpapers.service.wallpapers.AmazingWallpaper#onSurfaceChanged(int, int)
	 */
	@Override
	public void onSurfaceChanged(SurfaceHolder holder,int width, int height) {
		this.width = width;
		this.height =height;
	}

	/* (non-Javadoc)
	 * @see com.fmatos.amazingwallpapers.service.wallpapers.AmazingWallpaper#onTouchEvent(android.view.MotionEvent, android.view.SurfaceHolder)
	 */
	@Override
	public void onTouchEvent(MotionEvent event, SurfaceHolder holder) {
		if (touchEnabled) {

			int x = (int) event.getX();
			int y = (int) event.getY();
			
			Canvas canvas = null;
			try {
				canvas = holder.lockCanvas();
				if (canvas != null) {
					canvas.drawColor(Color.BLACK);
					circles.clear();
					Log.i(TAG,"add circle at " + x + "," + y);
					circles.add(new MyPoint(String.valueOf(circles.size() + 1), x, y));
					drawCircles(canvas, circles);

				}
			} finally {
				if (canvas != null)
					holder.unlockCanvasAndPost(canvas);
			}
			
		}
		
	}

	public void draw(SurfaceHolder holder) {
		Canvas canvas = null;
		try {
			canvas = holder.lockCanvas();
			if (canvas != null) {
				if (circles.size() >= maxNumber) {
					circles.clear();
				}
				int x = (int) (width * Math.random());
				int y = (int) (height * Math.random());
				circles.add(new MyPoint(String.valueOf(circles.size() + 1),
						x, y));
				drawCircles(canvas, circles);
			}
		} finally {
			if (canvas != null)
				holder.unlockCanvasAndPost(canvas);
		}
		
	}
	

	// Surface view requires that all elements are drawn completely
	private void drawCircles(Canvas canvas, List<MyPoint> circles) {
		canvas.drawColor(Color.BLACK);
		for (MyPoint point : circles) {
			canvas.drawCircle(point.getX(), point.getY(), 20.0f, paint);
		}
	}

	@Override
	public void onVisibilityChanged(boolean visible) {
		// TODO Auto-generated method stub
		
	}

}
